package cc.eddic.practice.concurrency.impl;

import cc.eddic.practice.concurrency.LogItem;
import cc.eddic.practice.concurrency.LogItemParser;
import lombok.extern.slf4j.Slf4j;
import lombok.val;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Locale;
import java.util.Optional;
import java.util.regex.Pattern;

@Slf4j
public class LogItemGZipParser implements LogItemParser {

    private static final Pattern PATTERN_LOG_LINE = Pattern.compile("(?<clientIP>.+) (?<hitMiss>.+) (?<responseTime>\\d+) \\[(?<timeZone>.+)] \"(?<method>\\w+) (?<url>.+) " +
                    "(?<protocol>\\S+?)\" (?<statusCode>\\d+) (?<trafficSize>\\d+) \"(?<referer>.*?)\" \"(?<userAgent>.*)\"",
            Pattern.UNICODE_CHARACTER_CLASS | Pattern.DOTALL);

    @Override
    public Optional<LogItem> parse(String line) {
        if (line == null) {
            return Optional.empty();
        }
        val m = PATTERN_LOG_LINE.matcher(line);
        if (!m.matches()) {
            log.error("Error parsing line: {}", line);
            return Optional.empty();
        }

//TODO 调整时间格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MMM/yyyy:HH:mm:ss Z", Locale.ENGLISH);
        LocalDateTime localtime = LocalDateTime.parse(m.group("timeZone"), formatter);
        return Optional.of(new LogItem(
                m.group("clientIP"),
                localtime,
                null,
                m.group("method"),
                m.group("url"),
                new HashMap<>(),
                m.group("protocol"),
                Integer.parseInt(m.group("statusCode"))
                , Long.parseLong(m.group("trafficSize")),
                m.group("referer"),
                m.group("userAgent")
        ));
    }
}
